package com.carreirati.evaluation;

import java.util.Iterator;
import java.util.List;

import com.carreirati.evaluation.domain.Appraisal;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@RequestMapping("/appraisals")
@Controller
@RooWebScaffold(path = "appraisals", formBackingObject = Appraisal.class)
@RooWebJson(jsonObject = Appraisal.class)
public class AppraisalController {
	
	 @RequestMapping(headers = "Accept=application/json")
	    @ResponseBody
	    public ResponseEntity<String> listJson() {
		   Authentication auth = SecurityContextHolder.getContext().getAuthentication();
	        String userIdLogged = auth.getName(); //get logged in username
	        
	        boolean showAsEvaluator = false;
	        
	        auth.getAuthorities().toArray()[0].toString();
	        String role = "";
	        for (int i=0;i< auth.getAuthorities().toArray().length;i++){
	        	role = auth.getAuthorities().toArray()[i].toString();
	        	if ((role.compareTo("ROLE_MANAGER") ==0) || (role.compareTo("ROLE_EVALUATOR") == 0)){
		        	   showAsEvaluator = true;
		           }
	        }

	     	HttpHeaders headers = new HttpHeaders();
	        headers.add("Content-Type", "application/json; charset=utf-8");
	        List<Appraisal> result = Appraisal.findAllAppraisalsByUserId(userIdLogged, showAsEvaluator);
	        return new ResponseEntity<String>(Appraisal.toJsonArray(result), headers, HttpStatus.OK);
	    }
	    
}
